package com.donn.securitycontrolplatform.config;

import com.donn.securitycontrolplatform.Interceptor.RestTemplateInterceptor;
import okhttp3.OkHttpClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RestTemplateConfig
 * @Author Glenn
 * @Date 2022/3/28 21:19
 * @Description Spring网络请求工具配置类
 * @Version 1.0
 */
@Configuration
public class RestTemplateConfig {


    /**
     * 没有实例化RestTemplate时，初始化RestTemplate
     *
     * @return
     */
    @ConditionalOnMissingBean(RestTemplate.class)
    @Bean
    public RestTemplate restTemplate() {
        //使用OkHttpClient作为底层客户端
        RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
        //指定拦截器
        restTemplate.setInterceptors(Collections.singletonList(restTemplateInterceptor()));
        return restTemplate;
    }

    /**
     * RestTemplate请求拦截器
     *
     * @return
     */
    @Bean
    public RestTemplateInterceptor restTemplateInterceptor() {
        return new RestTemplateInterceptor();
    }


    /**
     * 配置OkHttpClient超时信息等
     *
     * @return
     */
    private ClientHttpRequestFactory getClientHttpRequestFactory() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
        return new OkHttp3ClientHttpRequestFactory(okHttpClient);
    }


}
